package com.jiangyg.mall.authz.config;

import com.jiangyg.mall.authz.support.authentication.AccessDeniedExceptionHandler;
import com.jiangyg.mall.authz.support.authentication.AuthErrorExceptionHandler;
import com.jiangyg.mall.authz.support.authentication.AuthenticationRequestMatcher;
import com.jiangyg.mall.authz.support.authentication.admin.AdminRequestMatcher;
import com.jiangyg.mall.authz.support.authentication.member.MemberRequestMatcher;
import com.jiangyg.mall.core.support.web.MutilReaderHttpServletRequestWrapper;
import com.jiangyg.mall.core.utils.Logger;
import com.jiangyg.mall.core.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExceptionHandlingConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.access.ExceptionTranslationFilter;
import org.springframework.security.web.firewall.FirewalledRequest;
import org.springframework.security.web.firewall.RequestRejectedException;
import org.springframework.security.web.firewall.StrictHttpFirewall;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 类描述：安全认证核心配置
 * TODO 三个安全认证配置相互影响，需要处理
 *
 * @author jiangyg
 * @version 4.0
 * @date 2022-10-11
 */
@Slf4j
//@Order(0)
//@Configuration
public class SecurityCoreConfiguration extends WebSecurityConfigurerAdapter {

    private final List<RequestMatcher> requestMatchers;

    public SecurityCoreConfiguration() {
        requestMatchers = new ArrayList<>(2);
        requestMatchers.add(new MemberRequestMatcher());
        requestMatchers.add(new AdminRequestMatcher());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatcher(new AuthenticationRequestMatcher());
        // 禁用 CSRF
        http.csrf().disable();
        // session 策略
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        // 禁用缓存
        http.headers().cacheControl();
        // 访问权限前置过滤器（一定要在异常处理过滤器之后，否则异常不能正常处理）
        http.addFilterAfter(accessAuthenticationFilter(), ExceptionTranslationFilter.class);
        // 认证或者权限异常处理
        final ExceptionHandlingConfigurer<HttpSecurity> exceptionHandling = http.exceptionHandling();
        exceptionHandling.authenticationEntryPoint(new AuthErrorExceptionHandler());
        exceptionHandling.accessDeniedHandler(new AccessDeniedExceptionHandler());
    }

    /**
     * 功能描述：定义访问权限校验
     *
     * @return 访问权限校验
     */
    private GenericFilterBean accessAuthenticationFilter() throws Exception {
        return new GenericFilterBean() {

            @Override
            public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
                // 1. 请求类型判断
                if (!(servletRequest instanceof HttpServletRequest) || !(servletResponse instanceof HttpServletResponse)) {
                    throw new ServletException("TokenAuthenticationFilter 仅支持 HTTP 请求！");
                }
                final HttpServletRequest request = (HttpServletRequest) servletRequest;
                final HttpServletResponse response = (HttpServletResponse) servletResponse;
                // 2. 判断 cid 是否合法
                final boolean match = requestMatchers.stream().anyMatch(matcher -> matcher.matches(request));
                if (!match) {
                    throw new AccessDeniedException("请求没有指定cid类型！");
                }
                // 3. 继续执行过滤器
                chain.doFilter(servletRequest, servletResponse);
            }

        };
    }

    /**
     * 功能描述：重写请求，使请求能多次读取请求体内容
     * <p>注意：此方法实现初衷是为了解决 gateway 调用 feign 不能传递 header 、cookie ，目前此问题已解决，所以此方法可废弃</p>
     *
     * @return StrictHttpFirewall 请求
     */
    @Bean
    @Deprecated
    public StrictHttpFirewall strictHttpFirewall() {
        return new StrictHttpFirewall() {

            @Override
            public FirewalledRequest getFirewalledRequest(HttpServletRequest request) throws RequestRejectedException {
                try {
                    return super.getFirewalledRequest(new MutilReaderHttpServletRequestWrapper(request));
                } catch (IOException ex) {
                    Logger.error(log, () -> String.format("请求[%s]发生IO异常", WebUtils.getRequestPath(request), ex));
                    throw new RequestRejectedException("请求发生异常！");
                }
            }

        };
    }

}
